package com.transaction.demo.common.util;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.google.gson.reflect.TypeToken;

/**
 * 描述：http工具类
 * 作者：马庆智
 * 日期：2023/5/13 12:29
 */
public class OkHttpUtil {

	private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

	private static MediaType FORM_TYPE = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");
	private static final OkHttpClient client = new OkHttpClient();

	public static String post(String url, Object params) throws IOException {
		RequestBody body = RequestBody.create(JSON, JsonUtils.toJson(params));
		Request request = new Request.Builder().url(url).post(body).build();
		try (Response response = client.newCall(request).execute()) {
			return Objects.requireNonNull(response.body()).string();
		}
	}

	public static String postForm(String url, Object params) throws IOException {

		String toJson = JsonUtils.toJson(params);
		Map<String, String> paramsMap = JsonUtils.fromJson(toJson, new TypeToken<Map<String, String>>() {
		}.getType());

		FormBody.Builder formBody = new FormBody.Builder();

		if (paramsMap != null && !paramsMap.isEmpty()) {
			for (String key : paramsMap.keySet()) {
				formBody.add(key, paramsMap.get(key));
			}
		}
		Request request = new Request.Builder().url(url).addHeader("CONTENT_TYPE", FORM_TYPE.toString())
				.post(formBody.build()).build();
		try (Response response = client.newCall(request).execute()) {
			return Objects.requireNonNull(response.body()).string();
		}
	}

	public static String get(String url) throws IOException {
		Request request = new Request.Builder().url(url).build();

		try (Response response = client.newCall(request).execute()) {
			return Objects.requireNonNull(response.body()).string();
		}
	}
}
